package leetcode.L500;

public class Ex25 {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val,ListNode next) { this.val = val; this.next = next; }
    }
    public  static ListNode reverseKGroup(ListNode head, int k) {

        ListNode dumy = new ListNode(-1);
        dumy.next = head;
        ListNode preHead = dumy;

        while(head!=null){
            ListNode tail = preHead;
            for(int i = 0;i<k;i++){
                tail = tail.next;
                if(tail==null){
                    return dumy.next;
                }
            }
            ListNode tailNext = tail.next;
            ListNode[] res = reverse(head,tail);
            head = res[1];
            tail = res[0];
            head.next = tailNext;
            tail.next = preHead;

            preHead = head;
            head = preHead.next;
        }
        return dumy.next;


    }

    public static ListNode[] reverse(ListNode head,ListNode tail){
        ListNode pre = head;
        ListNode cur = head.next;
        while(pre!=tail){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return new ListNode[]{tail,head};
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode now = head;

        for (int i = 2; i <= 5 ; i++) {
            now.next = new ListNode(i);
            now = now.next;
        }


        reverseKGroup(head,2);
        while(head!=null){
            System.out.println(head.val);
            head = head.next;
        }

    }

}
